package protocol

import (
	"context"
	"net"

	"gitee.com/fzh-show/mcenter/conf"
	"gitee.com/fzh-show/mcenter/logger"

	"github.com/infraboard/mcube/ioc"

	"google.golang.org/grpc"
)

type Grpc struct {
	server *grpc.Server
}

// 如果http 服务器使用哪个路由, 当作参数传递进来
func NewGrpc() *Grpc {
	return &Grpc{
		server: grpc.NewServer(),
	}
}

func (g *Grpc) Start() error {
	// 1. 加载grpc业务实现类
	ioc.LoadGrpcController(g.server)
	logger.L().Debug().Msgf("loaded controllers: %s", ioc.ListControllerObjectNames())
	// 2. 启动
	lis, err := net.Listen("tcp", conf.C().Grpc.Address())
	if err != nil {
		return err
	}
	logger.L().Debug().Msgf("grpc server listen: %s", conf.C().Grpc.Address())
	return g.server.Serve(lis)
}

func (g *Grpc) Stop(ctx context.Context) {
	g.server.GracefulStop()
}
